package org.star.predicate;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.cloud.gateway.handler.predicate.AbstractRoutePredicateFactory;
import org.springframework.cloud.gateway.handler.predicate.GatewayPredicate;
import org.springframework.stereotype.Component;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.server.ServerWebExchange;

import java.util.Collections;
import java.util.List;
import java.util.function.Predicate;

/**
 * @Author : 一叶浮萍归大海
 * @Date: 2024/1/4 9:38
 * @Description: 自定义断言工厂
 * 功能：校验用户的权限，如果用户是已授权用户则放行，否则失败!
 */
@Component
public class AuthRoutePredicateFactory extends AbstractRoutePredicateFactory<AuthRoutePredicateFactory.Config> {

    public static final String AUTHED_USER = "admin";

    public AuthRoutePredicateFactory() {
        super(Config.class);
    }

    public List<String> shortcutFieldOrder() {
        return Collections.singletonList("name");
    }

    public Predicate<ServerWebExchange> apply(final Config config) {
        return new GatewayPredicate() {
            public boolean test(ServerWebExchange serverWebExchange) {
                if (AUTHED_USER.equals(config.getName())) {
                    return true;
                }
                return false;
            }
        };
    }

    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    @Validated
    public static class Config {
        private String name;
    }
    
}
